// src/utils/httpClient.ts
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { v4 as uuidv4 } from 'uuid';
import { getToken } from '@/utils/auth';
import router from '@/router';

export interface HttpResponse<T = unknown> {
  // 业务状态码，200-成功，其它-失败
  code: number;
  // 响应消息
  message: string;
  // 返回数据
  data: T;
  // 请求id
  requestId: string;
}

const apiClient: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000,
});

apiClient.interceptors.request.use(
  (config) => {
    if (config.headers) {
      config.headers['X-Request-ID'] = uuidv4();
      const accessToken = getToken();
      if (accessToken) {
        config.headers.Authorization = `Bearer ${accessToken}`;
      }
    }
    if (import.meta.env.DEV) {
      console.log(
        `[Request] ${config.method?.toUpperCase()} ${config.url}`,
        config,
      );
    }
    return config;
  },
  (error) => {
    if (import.meta.env.DEV) {
      console.error('[Request Error]', error);
    }
    return Promise.reject(error);
  },
);

apiClient.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    if (import.meta.env.DEV) {
      console.log(`[Response] ${response.config.url}`, response.data);
    }
    return response;
  },
  (error) => {
    if (import.meta.env.DEV) {
      console.error('[Response Error]', error);
    }
    const errorMessage =
      error.response?.data?.message || error.message || '服务器内部异常';
    Message.error({
      content: errorMessage,
      duration: 5 * 1000,
    });
    if (
      error.response.status === 401 &&
      error.response.data.message !== '用户名或密码错误'
    ) {
      router.replace(`/login?t=${Date.now()}`).then(() => {
        window.location.reload();
      });
    }
    return Promise.reject(error);
  },
);

export default apiClient;
